package com.sg.service.biz.app.nb;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.biz.app.req.*;
import com.sg.dto.biz.app.res.*;
import com.sg.dto.integration.component.QuerySemanticEngineDetailReqDto;
import com.sg.dto.integration.component.QuerySemanticEngineDetailRespDto;
import com.wicket.okrapp.common.baseinfo.BaseInfoDO;
import com.wicket.okrapp.common.baseinfo.BaseInfoHolder;
import com.wicket.okrcomponent.common.annotations.BanAuto;
import com.wicket.okrcomponent.integration.ConfSchemeService;
import com.wicket.okrcomponent.integration.TemplateEngineService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbEvaTheme {


    @Resource
    ConfSchemeService compConfSchemeClient;

    @Resource
    private TemplateEngineService fwCompTemplateEngineClient;

    /**
     * code:invokeQueryService
     * name:D2-3查应用实例配置关系详情(公共)
     * desc:undefined
     **/
    public QueryApplexConrelDetailComRespDto queryApplexConrelDetailCom(QueryApplexConrelDetailComReqDto reqDto) {

        return new QueryApplexConrelDetailComRespDto();
    }


    /**
     * code:columnToRow
     * name:M3目标规划模板子类型等列转行
     * desc:undefined
     **/
    @BanAuto
    public TransitionConfItemResultToAnswerRespDto transitionConfItemResultToAnswer(TransitionConfItemResultToAnswerReqDto reqDto) {
        TransitionConfItemResultToAnswerRespDto retData = new TransitionConfItemResultToAnswerRespDto();
        for (ConfSchemeItemResultDto oneItem : reqDto.getConfSchemeItemResultList()) {

            retData.setConfSchemeId(oneItem.getConfSchemeId());
            String code = CommonFunctionHelper.underlineToHump(oneItem.getConfItemCode());
            if (code.equals("bizSceneCode")) {
                retData.setBizSceneCode(oneItem.getEndValue());
            }
            if (code.equals("evaluationSubjectTypeCode")) {
                retData.setEvaluationSubjectTypeCode(oneItem.getEndValue());
            }
            if (code.equals("isOkrPlanScene")) {
                retData.setIsOkrPlanScene(oneItem.getEndValue());
            }
            if (code.equals("evaluationTemplateTypeCode")) {
                retData.setEvaluationTemplateTypeCode(oneItem.getEndValue());
            }
            if (code.equals("targetPlanTempSubtype")) {
                retData.setTargetPlanTempSubtype(oneItem.getEndValue());
            }
            if (code.equals("planningType")) {
                retData.setPlanningType(oneItem.getEndValue());
            }
            if (code.equals("useObjectTypeCode")) {
                retData.setUseObjectTypeCode(oneItem.getEndValue());
            }
            if (code.equals("okrType")) {
                retData.setOkrType(oneItem.getEndValue());
            }
            if (code.equals("evaThemeHostTypeCode")) {
                retData.setEvaThemeHostTypeCode(oneItem.getEndValue());
            }
            if (code.equals("cycleMode")) {
                retData.setCycleMode(oneItem.getEndValue());
            }
            if (code.equals("openMidCycle")) {
                retData.setOpenMidCycle(oneItem.getEndValue());
            }
            if (code.equals("cycleSystemCode")) {
                retData.setCycleSystemCode(oneItem.getEndValue());
            }
            if (code.equals("fatherCycleType")) {
                retData.setFatherCycleType(oneItem.getEndValue());
            }
            if (code.equals("midCycleType")) {
                retData.setMidCycleType(oneItem.getEndValue());
            }
            if (code.equals("subcycleType")) {
                retData.setSubcycleType(oneItem.getEndValue());
            }
            if (code.equals("monocycleCycleType")) {
                retData.setMonocycleCycleType(oneItem.getEndValue());
            }
            if (code.equals("isOpenEvaWork")) {
                retData.setIsOpenEvaWork(oneItem.getEndValue());
            }
            if (code.equals("isOpenFillWork")) {
                retData.setIsOpenFillWork(oneItem.getEndValue());
            }
            if (code.equals("isOpenAtuoAssBatch")) {
                retData.setIsOpenAtuoAssBatch(oneItem.getEndValue());
            }
            if (code.equals("timeCountReferTime")) {
                retData.setTimeCountReferTime(Long.valueOf(oneItem.getEndValue()));
            }
            if (code.equals("timeRulesSetLevel")) {
                retData.setTimeRulesSetLevel(oneItem.getEndValue());
            }
            if (code.equals("isCustomTimeRules")) {
                retData.setIsCustomTimeRules(oneItem.getEndValue());
            }
            if (code.equals("fillTimeRulesCode")) {
                retData.setFillTimeRulesCode(oneItem.getEndValue());
            }
            if (code.equals("evaTimeRulesCode")) {
                retData.setEvaTimeRulesCode(oneItem.getEndValue());
            }
        }
        return retData;
    }


    /**
     * code:generateSemanticInstance
     * name:M生成名称（不规则周期名称）
     * desc:undefined
     **/
    public GenerateNameResDto generateName(GenerateNameReqDto reqDto) {

        return new GenerateNameResDto();
    }

    /**
     * code:getRootCode
     * name:M3获取目标标识（特殊方法）
     * desc:undefined
     **/
    public ObtainTargetCodeResDto obtainTargetCode(ObtainTargetCodeReqDto reqDto) {
        return new ObtainTargetCodeResDto();
    }


    /**
     * code:invokeQueryService
     * name:D2-3查目标规划模板子类型等
     * desc:undefined
     **/
    public QuerySchemeClassMatchAnswerListComBorderResDto querySchemeClassMatchAnswerListComBorder(QuerySchemeClassMatchAnswerListComBorderReqDto reqDto) {
        return new QuerySchemeClassMatchAnswerListComBorderResDto();
    }

    /**
     * code:getFirstDayAfterCycle
     * name:M3获取周期结束第1天(特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M3获取周期结束第1天(特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainCycleEndFirstDayResDto obtainCycleEndFirstDay(ObtainCycleEndFirstDayReqDto reqDto) {
        return new ObtainCycleEndFirstDayResDto();
    }

    /**
     * code:invokeQueryService
     * name:D2-3查配置项匹配答案列表(过程阶段周期类型)（跨服务）
     * desc:undefined
     **/
    @Trace(operationName = "D2-3查配置项匹配答案列表(过程阶段周期类型)（跨服务）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryConfItemMatchAnswerListComResDto queryConfItemMatchAnswerListCom(QueryConfItemMatchAnswerListComReqDto reqDto) {
        return new QueryConfItemMatchAnswerListComResDto();
    }

    /**
     * code:invokeQueryService
     * name:D2-3查配置项匹配答案详情(末级周期类型)（跨服务）
     * desc:undefined
     **/
    @Trace(operationName = "D2-3查配置项匹配答案详情(末级周期类型)（跨服务）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryConfItemMatchAnswerDetailComResDto queryConfItemMatchAnswerDetailCom(QueryConfItemMatchAnswerDetailComReqDto reqDto) {
        return new QueryConfItemMatchAnswerDetailComResDto();
    }

    /**
     * code:getTargetCycle
     * name:M3获取当前目标周期(特殊方法)
     * desc:undefined
     **/
    @Trace(operationName = "M3获取当前目标周期(特殊方法)")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainCurrentTargetCycleResDto obtainCurrentTargetCycle(ObtainCurrentTargetCycleReqDto reqDto) {
        return new ObtainCurrentTargetCycleResDto();
    }

    /**
     * code:calcReferenceTime
     * name:M3生成计算参照时间（特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M3生成计算参照时间（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateCountReferenceTimeResDto generateCountReferenceTime(GenerateCountReferenceTimeReqDto reqDto) {
        return new GenerateCountReferenceTimeResDto();
    }

    /**
     * code:getObjectCode
     * name:M3获取对象标识（特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M3获取对象标识（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @BanAuto
    public ObtainObjectCodeRespDto obtainObjectCode(ObtainObjectCodeReqDto reqDto) {
        ObtainObjectCodeRespDto retData = new ObtainObjectCodeRespDto();
        if (CollUtil.isEmpty(reqDto.getObjectCodeList())) {
            List<Long> codeNumList = reqDto.getObjectCodeList().stream().map(code -> Long.parseLong(code)).collect(Collectors.toList());
            Long max = Collections.max(codeNumList);
            max = max + 1;
            retData.setObjectCode(String.valueOf(max));
        } else {
            String code = reqDto.getSuperiorCode();
            code = code + "1001";
            retData.setObjectCode(code);
        }
        return retData;
    }

    /**
     * code:receptionService
     * name:M-查方案下选项配置结果(公共)（特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M-查方案下选项配置结果(公共)（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryConfItemResultDetailComRespDto queryConfItemResultDetailCom(QueryConfItemResultDetailComReqDto reqDto) {
        return new QueryConfItemResultDetailComRespDto();
    }

    /**
     * code:generateSemanticInstance
     * name:M生成评价模板批次名称
     * desc:undefined
     * gen by moon at 8/29/2022, 1:06:07 AM
     **/
    @Trace(operationName = "M生成评价模板批次名称")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateSemanticContentRespDto generateSemanticContent(GenerateSemanticContentReqDto reqDto) {
        //{systemDateTime}{sixRandomNum}{targetContName}批次
        boolean bRetFlag = false;
        GenerateSemanticContentRespDto retData = new GenerateSemanticContentRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("CREATE_TEMP_BATCH_NAME");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String targetContName = "\\{targetContName}";
            String systemDateTime = "\\{systemDateTime}";
            String sixRandomNum = "\\{sixRandomNum}";
            if (reqDto.getTargetContentName() != null && !reqDto.getTargetContentName().isEmpty()) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContName, reqDto.getTargetContentName());
                retConent = retConent.replaceAll(systemDateTime, CommonFunctionHelper.date2Str(CommonFunctionHelper.getCurrentTime()));
                retConent = retConent.replaceAll(sixRandomNum, String.valueOf((Math.random() * 9 + 1) * 100000));
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContName, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:specialMethodOutputPara
     * name:模板是否开启评价工作
     * desc:undefined
     * gen by moon at 9/6/2022, 2:48:44 AM
     **/
    @Trace(operationName = "模板是否开启评价工作")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddOutputParametersRespDto addOutputParameters(AddOutputParametersReqDto reqDto) {
        return BeanUtil.toBean(reqDto, AddOutputParametersRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3-传输数值1
     * desc:undefined
     * gen by moon at 9/9/2022, 8:38:16 PM
     **/
    @Trace(operationName = "M3-传输数值1")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainReceiveFieldRespDto obtainReceiveField(ObtainReceiveFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ObtainReceiveFieldRespDto.class);
    }

    /**
     * code:collectionsMergeData
     * name:M3生成角色数据集聚合(特殊方法）
     * desc:undefined
     * gen by moon at 9/14/2022, 5:37:35 PM
     **/
    @Trace(operationName = "M3生成角色数据集聚合(特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateCollectionsAggregationRespDto generateCollectionsAggregation(GenerateCollectionsAggregationReqDto reqDto) {
        GenerateCollectionsAggregationRespDto retData = new GenerateCollectionsAggregationRespDto();
        for (FrameworkSceneRoleDto one : reqDto.getRoleList()) {
            FrameworkSceneRoleDto elm = BeanUtil.toBean(one, FrameworkSceneRoleDto.class);
            retData.getRoleList().add(elm);
            for (ConfSchemeItemResultDto subOne : reqDto.getConfSchemeItemResultList()) {
                if (subOne.getEndValue().equals(one.getRoleCode())) {
                    elm.setNumber(subOne.getConfOptionSortNum());
                }
            }
        }
        return retData;
    }

    /**
     * code:receptionService
     * name:模板未开启评价工作
     * desc:undefined
     * gen by moon at 9/21/2022, 12:41:17 AM
     **/
    @Trace(operationName = "模板未开启评价工作")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementOutputParametersRespDto implementOutputParameters(ImplementOutputParametersReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementOutputParametersRespDto.class);
    }

    /**
     * code:publicFieldCache
     * name:M3执行业务应用公共字段推送内存（特殊方法）
     * desc:undefined
     * gen by moon at 10/10/2022, 6:31:41 PM
     **/
    @Trace(operationName = "M3执行业务应用公共字段推送内存（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizPublicFieldPushMemoryRespDto implementBizPublicFieldPushMemory(ImplementBizPublicFieldPushMemoryReqDto reqDto) {
        BaseInfoDO domain = new BaseInfoDO();
        if (BaseInfoHolder.contextHolder.get() != null) {
            BeanUtil.copyProperties(BaseInfoHolder.contextHolder.get().getBaseInfo(), domain);
            BaseInfoHolder.contextHolder.remove();
        }
        if (reqDto.getSpaceId() != null) {
            domain.setSpecSpaceId(reqDto.getSpaceId());
        }

        if (reqDto.getCreateInductionId() != null) {
            domain.setSpecInductionRecordId(reqDto.getCreateInductionId());
        }

        if (reqDto.getAppId() != null) {
            domain.setSpecAppId(reqDto.getAppId());
        }

        if (reqDto.getHighestOrgID() != null) {
            domain.setSpecHighestOrgID(reqDto.getHighestOrgID());
        }

        if (reqDto.getUserId() != null) {
            domain.setSpecUserId(reqDto.getUserId());
        }

        if (reqDto.getOriginalRoleMemberId() != null) {
            domain.setSpecOriginalRoleMemberId(reqDto.getOriginalRoleMemberId());
        }

        CommonFunctionHelper.setBaseInfoToLocal(domain);
        return new ImplementBizPublicFieldPushMemoryRespDto();
    }

    /**
     * code:generateSemanticInstance
     * name:M生成评价模板批次名称
     * desc:undefined
     * gen by moon at 10/10/2022, 9:33:27 PM
     **/
    @Trace(operationName = "M生成评价模板批次名称")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateEvaTempBatchNameRespDto generateEvaTempBatchName(GenerateEvaTempBatchNameReqDto reqDto) {


        // {systemDateTime}{randomNumberDigits}{targetContentName}批次

        boolean bRetFlag = false;
        GenerateEvaTempBatchNameRespDto retData = new GenerateEvaTempBatchNameRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("GENERATE_EVA_TEMP_BATCH_NAME");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String systemDateTime = "\\{systemDateTime}";
            String randomNumberDigits = "\\{randomNumberDigits}";
            String targetContentName = "\\{targetContentName}";
            if (reqDto.getTargetContentName() != null && !reqDto.getTargetContentName().isEmpty()) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContentName, reqDto.getTargetContentName());
                retConent = retConent.replaceAll(systemDateTime, CommonFunctionHelper.date2Str(CommonFunctionHelper.getCurrentTime()));
                Random random = new Random();
                String result = "";
                for (int i = 0; i < reqDto.getRandomNumberDigits(); i++) {
                    result += random.nextInt(10);
                }
                retConent = retConent.replaceAll(randomNumberDigits, result);
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContentName, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:receptionService
     * name:M3有新增模板权限
     * desc:undefined
     * gen by moon at 10/10/2022, 9:34:43 PM
     **/
    @Trace(operationName = "M3有新增模板权限")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainReceiveOutFieldRespDto obtainReceiveOutField(ObtainReceiveOutFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ObtainReceiveOutFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3接收上文出参参数
     * desc:undefined
     * gen by moon at 2/6/2023, 5:56:51 PM
     **/
    @Trace(operationName = "M3接收上文出参参数")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAccessParameterBizFieldRespDto implementAccessParameterBizField(ImplementAccessParameterBizFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAccessParameterBizFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3约定为允许新增评价模板
     * desc:undefined
     * gen by moon at 5/1/2023, 10:17:45 PM
     **/
    @Trace(operationName = "M3约定为允许新增评价模板")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAcceptFieldRespDto implementAcceptField(ImplementAcceptFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAcceptFieldRespDto.class);
    }


    // 手工接入方法
}
